from django.db import models
from django.conf import settings
from django.core.validators import MinValueValidator
from decimal import Decimal
from products.models import Product


class Order(models.Model):
    """订单模型"""
    STATUS_CHOICES = [
        ('pending', '待付款'),
        ('paid', '已付款'),
        ('processing', '处理中'),
        ('shipped', '已发货'),
        ('delivered', '已送达'),
        ('cancelled', '已取消'),
        ('refunded', '已退款'),
    ]

    PAYMENT_METHODS = [
        ('alipay', '支付宝'),
        ('wechat', '微信支付'),
        ('credit_card', '信用卡'),
        ('bank_transfer', '银行转账'),
        ('cash_on_delivery', '货到付款'),
    ]

    order_number = models.CharField('订单号', max_length=32, unique=True)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        verbose_name='用户',
        related_name='orders'
    )

    status = models.CharField('订单状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    payment_method = models.CharField('支付方式', max_length=20, choices=PAYMENT_METHODS, blank=True)

    # 收货信息
    shipping_name = models.CharField('收货人', max_length=100)
    shipping_phone = models.CharField('联系电话', max_length=20)
    shipping_address = models.TextField('收货地址')
    shipping_postal_code = models.CharField('邮政编码', max_length=10, blank=True)

    # 价格信息
    subtotal = models.DecimalField(
        '商品小计',
        max_digits=10,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0'))]
    )
    shipping_cost = models.DecimalField(
        '运费',
        max_digits=10,
        decimal_places=2,
        default=Decimal('0'),
        validators=[MinValueValidator(Decimal('0'))]
    )
    discount_amount = models.DecimalField(
        '优惠金额',
        max_digits=10,
        decimal_places=2,
        default=Decimal('0'),
        validators=[MinValueValidator(Decimal('0'))]
    )
    total_amount = models.DecimalField(
        '总金额',
        max_digits=10,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0'))]
    )

    # 时间信息
    created_at = models.DateTimeField('下单时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    paid_at = models.DateTimeField('付款时间', null=True, blank=True)
    shipped_at = models.DateTimeField('发货时间', null=True, blank=True)
    delivered_at = models.DateTimeField('送达时间', null=True, blank=True)

    # 备注
    notes = models.TextField('订单备注', blank=True)
    admin_notes = models.TextField('管理员备注', blank=True)

    class Meta:
        verbose_name = '订单'
        verbose_name_plural = '订单管理'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', 'created_at']),
            models.Index(fields=['user', 'status']),
        ]

    def __str__(self):
        return f"订单{self.order_number} - {self.user.username}"

    def save(self, *args, **kwargs):
        if not self.order_number:
            import uuid
            from datetime import datetime
            timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
            self.order_number = f'ORD{timestamp}{str(uuid.uuid4())[:8].upper()}'
        super().save(*args, **kwargs)


class OrderItem(models.Model):
    """订单项目模型"""
    order = models.ForeignKey(
        Order,
        on_delete=models.CASCADE,
        related_name='items',
        verbose_name='订单'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        verbose_name='产品'
    )

    quantity = models.PositiveIntegerField('数量')
    unit_price = models.DecimalField(
        '单价',
        max_digits=10,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0.01'))]
    )
    total_price = models.DecimalField(
        '小计',
        max_digits=10,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0'))]
    )

    # 产品快照，防止产品信息变更
    product_name = models.CharField('产品名称快照', max_length=200)
    product_image = models.URLField('产品图片快照', blank=True)

    class Meta:
        verbose_name = '订单项目'
        verbose_name_plural = '订单项目管理'
        unique_together = ['order', 'product']

    def __str__(self):
        return f"{self.order.order_number} - {self.product_name} x {self.quantity}"

    def save(self, *args, **kwargs):
        # 自动计算小计
        self.total_price = self.quantity * self.unit_price
        # 保存产品快照
        if not self.product_name:
            self.product_name = self.product.name
        if not self.product_image and self.product.image:
            self.product_image = self.product.image.url
        super().save(*args, **kwargs)


class OrderStatusHistory(models.Model):
    """订单状态历史记录"""
    order = models.ForeignKey(
        Order,
        on_delete=models.CASCADE,
        related_name='status_history',
        verbose_name='订单'
    )
    from_status = models.CharField('原状态', max_length=20, blank=True)
    to_status = models.CharField('新状态', max_length=20)
    reason = models.TextField('变更原因', blank=True)
    operator = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name='操作人'
    )
    created_at = models.DateTimeField('操作时间', auto_now_add=True)

    class Meta:
        verbose_name = '订单状态历史'
        verbose_name_plural = '订单状态历史'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.order.order_number}: {self.from_status} -> {self.to_status}"
